import axios from 'axios'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import router from '../router'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL:'api/',
  // baseURL:'index.php',
  baseURL: process.env.NODE_ENV === 'production' ? '../' : '/api',
  timeout: 6000 // 请求超时时间
})
// 异常拦截处理器
const errorHandler = (error) => {
  console.log('错误处理', error)
  if (error.data) {
    const data = error.data
    // 从 localstorage 获取 token
    if (data.ret === 400) {
      notification.error({
        message: '参数错误',
        description: data.msg
      })
    }
    if (data.ret === 401) {
      notification.error({
        message: '登录失效，请重新登录',
        description: '无操作2小时后，登录失效'
      })
      localStorage.clear();
      router.push('/user/login');
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (localStorage.getItem('token') != '' && localStorage.getItem('token') != null && localStorage.getItem('token') != undefined) {
    let datas = {};
    if( config.data != undefined ){
      datas = config.data
    }else{
      datas = {}
    }
  // datas.users_id = localStorage.getItem('users_id')
  datas['token'] = window.localStorage.getItem('token');
  config.data = datas;
  
    // config.data['token'] = window.localStorage.getItem('token');
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if (response.data.ret === 200) {
    return response.data
  } else if(response.data.ret === 400) {
    errorHandler(response)
  }else{
    errorHandler(response)
  }
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
